package com.heima.search.listen;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.message.ArticleForEsConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class ArticleAddOrRemoveListener {
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private ArticleSearchService articleSearchService;


    /**
     * 向索引库中添加文档
     */
    @KafkaListener(topics = ArticleForEsConstants.ARTICLE_ELASTICSEARCH_ADD)
    public void addArticle(String message) {
        log.info("搜索微服务 收到消息开始往索引库中添加文档===>{}", message);
        //解析消息
        Map map = JSON.parseObject(message, Map.class);
        System.out.println("map = " + map);
        String articleId = String.valueOf(map.get("articleId"));
        //根据id查询出文章对象
        ResponseResult<SearchArticleVo> responseResult = articleFeign.findArticle(Long.valueOf(articleId));
        if (responseResult.getCode() != 0) {
            log.error("articleFeign 远程调用 findArticle失败，错误原因：{}，参数：{}", responseResult.getErrorMessage(), articleId);
            CustomException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
        SearchArticleVo articleVo = responseResult.getData();
        articleSearchService.saveArticle(articleVo);
        log.info("搜索微服务 往索引库中添加文档成功");
    }

    /**
     * 从索引库中删除文档
     */
    @KafkaListener(topics = ArticleForEsConstants.ARTICLE_ELASTICSEARCH_DELETE)
    public void deleteArticle(String message) {
        log.info("搜索微服务 收到消息开始删除索引库中的文档===>{}", message);
        Map map = JSON.parseObject(message, Map.class);
        String articleId = (String) map.get("articleId");
        articleSearchService.deleteArticle(Long.valueOf(articleId));
        log.info("搜索微服务 删除id：{}文档成功", articleId);
    }
}
